package chat

import (
	"sanguo/node/common/com_type"
	"sanguo/node/node_chat"
	excel "sanguo/node/table/excel/table"
	table_Map "sanguo/node/table/excel/table/Map"

	"github.com/sniperHW/kendynet/event"
)

type Chat struct {
	Type  int32
	ID    int32
	Roles map[uint64]*Role
}

var chatMgr *ChatManager

type ChatManager struct {
	Roles        map[uint64]*Role
	MapChats     map[int32]*Chat
	TeamChats    map[int32]*Chat
	processQueue *event.EventQueue
}

func (this *ChatManager) PostTask(task func()) {
	this.processQueue.Post(task)
}

//队伍
func (this *ChatManager) CreateTeamChat(teamID int32) *Chat {
	teamChat := &Chat{
		Type: com_type.Chat_Team,
		ID:   teamID,
	}
	this.TeamChats[teamID] = teamChat
	return teamChat
}

func (this *Role) EnterTeamChat(teamID int32) {
	teamChat := chatMgr.TeamChats[teamID]
	if teamChat == nil {
		teamChat = chatMgr.CreateTeamChat(teamID)
	}

	this.SetTeamChat(teamChat)
	teamChat.Roles[this.GetRoleID()] = this

}

//地图
func (this *Chat) GetMapRolos() map[uint64]*Role {
	return this.Roles
}

func (this *Role) ChangeMapChat(mapID int32) bool {
	mapChat := chatMgr.MapChats[mapID]
	if mapChat == nil {
		return false
	}

	if this.GetMapChat() != nil {
		r := this.GetMapChat().Roles[this.GetRoleID()]
		if r != nil {
			delete(this.mapChat.Roles, r.GetRoleID())
			this.SetMapChat(nil)
		}
	}

	this.SetMapChat(mapChat)
	mapChat.Roles[this.GetRoleID()] = this

	return true
}

//进入聊天
func (this *ChatManager) EnterChat(role *Role) bool {
	this.Roles[role.GetRoleID()] = role
	return true
}

func (this *ChatManager) LeaveChat(role *Role) {

	if role.GetTeamChat() != nil {
		delete(role.teamChat.Roles, role.GetRoleID())
		role.SetTeamChat(nil)
	}

	if role.GetMapChat() != nil {
		delete(role.mapChat.Roles, role.GetRoleID())
		role.SetMapChat(nil)
	}

	delete(this.Roles, role.GetRoleID())

}

func InitMapChat(mapID int32) {
	mapChat := &Chat{
		Type:  com_type.Chat_Map,
		ID:    mapID,
		Roles: map[uint64]*Role{},
	}
	chatMgr.MapChats[mapID] = mapChat

	node_chat.Infoln("node_chat InitMapChat :", mapChat)
}

func Init() bool {
	excel.Load("table/excel/table/")

	if len(table_Map.Table_.IDMap) < 1 {
		return false
	}

	for _, v := range table_Map.Table_.IDMap {
		InitMapChat(v.ID)
	}
	return true
}

func init() {
	chatMgr = &ChatManager{
		Roles:        map[uint64]*Role{},
		MapChats:     map[int32]*Chat{},
		TeamChats:    map[int32]*Chat{},
		processQueue: event.NewEventQueue(),
	}
	go func() {
		chatMgr.processQueue.Run()
	}()
}
